# -*- coding:utf-8 -*-
'''
Created on 2012. 3. 8.

@author: weonseoggim
'''
import unittest
from cStringIO   import StringIO
from xml.etree   import cElementTree as etree
import xml.etree.ElementTree as xml
from xml.dom.minidom import Document
import codecs

class Test(unittest.TestCase):

    xmlname="./catalog.xml"
    
        
    def setUp(self):
        pass


    def tearDown(self):
        pass


    def testXMLCategory(self):
        root = xml.Element('root')
        child = xml.Element('child')
        root.append(child)
        child.attrib['name'] = "Charlie"
        child.text="HI"
        file = open(self.xmlname, 'w')
        xml.ElementTree(root).write(file)
        file.close()     
        
        pass

    def testXMLRead(self):
        print ">> testXMLRead>>>"
        file = open(self.xmlname,"r")
        readdata = file.read()
        for event, elem in etree.iterparse(StringIO(readdata)):
            print elem.text

        pass
    
#    한글처리 
    def euckrToUTF8(self ,hangul):
        return unicode(hangul, 'euc-kr').encode('utf-8')


    
    def testCreateMiniDom(self):
        print "testCreateMiniDom"
        doc = Document()
        root = doc.createElement("root")
        doc.appendChild(root)
        
        store = doc.createElement("storeaddr")
        if store:
            root.appendChild(store)
            
            storeurl = doc.createElement("url")
            storeurl.appendChild(doc.createTextNode("host/dasin/store_key"))
            store.appendChild(storeurl)

            store_title = doc.createElement("title")
            store_title.appendChild(doc.createTextNode("중앙학원"))
#            store_title.appendChild(doc.createTextNode(self.euckrToUTF8("중앙학원")))
            store.appendChild(store_title)
        
        books= doc.createElement("books")
        root.appendChild(books)
        for i in range(5):
            if books :
                book = doc.createElement("book")
                book.setAttribute("code", str(i))
#                타이틀 
                book_title=doc.createElement("title")
                book_title_value=doc.createTextNode("중간고사기출")
                book_title.appendChild(book_title_value)
                book.appendChild(book_title)
                
                url = doc.createTextNode("data.zip")
                book.appendChild(url)
#                book.set
                books.appendChild(book)
        
        print doc.toprettyxml(indent=" ")
        
        # Opening file for writing UTF-8, which is XML's default encoding
        f = codecs.open('./store.xml', mode='w', encoding='utf-8')
#        f.write(doc.toxml("utf-8"))
        # Writing XML in UTF-8 encoding, as recommended in the documentation
        doc.writexml(f, encoding="utf=8")
        f.close()


if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()